package siruna.WE.core.BlockFactory;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.zip.ZipFile;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import siruna.WE.core.events.EventListener;
import siruna.WE.core.model.FunctionalBlock;

public class FunctionalBlockFactory {

	LinkedHashMap<String, FunctionalBlock> funcBlocks;
	EventListener eventlistener;
	private ZipFile zipFile;
	private String deviceDependentFunctionBlocks;
	private String widgetName;

	public FunctionalBlockFactory(EventListener eventhandler, ZipFile zipFile,
			String deviceDependentFunctionBlocks, String widgetName) {
		funcBlocks = new LinkedHashMap<String, FunctionalBlock>();
		this.eventlistener = eventhandler;
		this.zipFile = zipFile;
		this.deviceDependentFunctionBlocks = deviceDependentFunctionBlocks;
		this.widgetName = widgetName;
	}

	public HashMap<String, FunctionalBlock> makeFunctionalBlocks(NodeList vis) {
		for (int i = 0; i < vis.getLength(); i++) {
			Node n = vis.item(i);
			behandelNode(n);
		}

		return funcBlocks;
	}

	private void behandelNode(Node n) {

		NodeList list = n.getChildNodes();
		for (int i = 0; i < list.getLength(); i++) {
			if (list.item(i).getNodeType() == Document.ELEMENT_NODE) {
				createFunctionalBlock(list.item(i));
			}
		}

	}

	private void createFunctionalBlock(Node n) {
		NamedNodeMap att = n.getAttributes();
		// Functional t =
		// Constants.Functional.valueOf(n.getNodeName().toLowerCase());
		FunctionalBlock f = null;

		Class calc;
		try {
			
				calc = Class.forName("siruna.WE.core.model.FunctionalBlocks."
						+ n.getNodeName() + "Impl");
			

			f = (FunctionalBlock) calc.newInstance();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/*
		 * switch (t) { case imageloader: ImageLoader il = new ImageLoader();
		 * 
		 * f = il; break;
		 * 
		 * }
		 */
		if (f != null) {
			f.setEventHandler(eventlistener);
			setIdAndAttributes(att, f);
			f.setWidgetName(widgetName);
			save(f);
		}
	}

	private void save(FunctionalBlock b) {
		funcBlocks.put(b.getId(), b);

	}

	private void setIdAndAttributes(NamedNodeMap att, FunctionalBlock fb) {
		fb.setId(att.getNamedItem("Id").getNodeValue());
		att.removeNamedItem("Id");
		for (int i = 0; i < att.getLength(); i++) {
			fb.setAttribute(att.item(i).getNodeName(), att.item(i)
					.getNodeValue());
		}
	}

}
